package br.sgd.model.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.sgd.model.beans.Documento;
import br.sgd.utils.HibernateUtil;

public class DocumentoDao {

	public void salvar(Documento documento){
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(documento);
		tx.commit();
		session.close();
	}

	public void excluir(Documento documento){
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.delete(documento);
		tx.commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	public List<Documento> listarTodos() {
		Session session = HibernateUtil.getSession();
		try {
			return session.createCriteria(Documento.class).addOrder(Order.desc("nome")).list();
		} finally {
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Documento> filtrar(Documento documento) {
		Session session = HibernateUtil.getSession();
		try {
			Criteria criteria = session.createCriteria(Documento.class).addOrder(Order.desc("nome"));
			if(documento.getNome()!=null && !documento.getNome().equals("")) criteria.add(Restrictions.ilike("nome", "%"+documento.getNome()+"%"));
			if(documento.getUsuario()!=null && !documento.getUsuario().equals("")) criteria.add(Restrictions.eq("usuario", documento.getUsuario()));
			if(documento.getData()!=null) {
				Date dataSup = (Date) documento.getData().clone();
				dataSup.setHours(23);
				dataSup.setMinutes(59);
				dataSup.setSeconds(59);
				criteria.add(Restrictions.between("data", documento.getData(), dataSup));
				
			}
			
	
			return criteria.list();
		} finally {
			session.close();
		}
	}
}
